const fs = require('fs')
const express = require('express')

const router = express.Router()
//新增
router.post('/add', (req, res) => {
    // console.log(req.body)
    const data = fs.readFileSync('./data/cart.json')
    const list = JSON.parse(data)
    list.push({
        name: req.body.name,
        id: Date.now()
    })
    fs.writeFileSync('./data/cart.json', JSON.stringify(list))
    res.send('新增成功')
})


//修改
router.post('/modified', (req, res) => {
    const data = fs.readFileSync('./data/cart.json')
    const list = JSON.parse(data)
    const index = list.findIndex(item => item.id == req.body.id)
    // console.log(index)
    list[index].name = req.body.name
    fs.writeFileSync('./data/cart.json', JSON.stringify(list))
    res.send('修改成功')
})

//删除
router.get('/delete', (req, res) => {
    const data = fs.readFileSync('./data/cart.json')
    const deletelist = JSON.parse(data)
    const index = list.findIndex(item => item.id == req.body.id)
    list.splice(index, 1)
    fs.writeFileSync('./data/cart.json', JSON.stringify(list))
    res.send('删除成功')
})

router.get('/search', (req, res) => {
    const data = fs.readFileSync('./data/cart.json')
    res.send(data)
})


module.exports = router